package xyz.chaobei.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import xyz.chaobei.mall.mapper.UmsAdminRoleRelationMapper;
import xyz.chaobei.mall.model.UmsAdminRoleRelationModel;
import xyz.chaobei.mall.pojo.UmsAdminRoleRelationSaveAO;
import xyz.chaobei.mall.service.UmsAdminRoleRelationService;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户关联角色 Service impl
 *
 * @author mrc
 * @since 2020-10-29 16:36:51
 */
@Service
public class UmsAdminRoleRelationServiceimpl implements UmsAdminRoleRelationService {

    @Autowired
    private UmsAdminRoleRelationMapper umsAdminRoleRelationMapper;

    @Override
    public boolean save(UmsAdminRoleRelationSaveAO params) {

        UmsAdminRoleRelationModel model = new UmsAdminRoleRelationModel();
        BeanUtils.copyProperties(params, model);
        /**
         * 你的逻辑写在这里
         */
        int num = umsAdminRoleRelationMapper.insert(model);

        return SqlHelper.retBool(num);
    }

    @Override
    public boolean deleteById(Integer id) {

        /**
         * 你的逻辑写在这里
         */
        int num = umsAdminRoleRelationMapper.deleteById(id);
        return SqlHelper.retBool(num);
    }

    @Override
    public List<Integer> queryAdminRoleIds(Integer id) {
        List<UmsAdminRoleRelationModel> result = umsAdminRoleRelationMapper.selectList(new QueryWrapper<UmsAdminRoleRelationModel>().eq("admin_id", id));
        return result.stream().map(item -> item.getRoleId()).collect(Collectors.toList());
    }
    @Override
    public boolean updateAdminRole(Integer userId, List<Integer> roleIds) {

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("`admin_id`", userId);

        int num = umsAdminRoleRelationMapper.delete(wrapper);

        UmsAdminRoleRelationModel model = new UmsAdminRoleRelationModel();
        for (Integer role : roleIds) {

            model.setId(null);
            model.setAdminId(userId);
            model.setRoleId(role);

            umsAdminRoleRelationMapper.insert(model);
        }
        return SqlHelper.retBool(num);
    }

}
